package svc

import (
	"encoding/json"
	"fmt"

	"mall/common/errorx"
	"mall/service/backend/api/internal/config"

	"github.com/elastic/go-elasticsearch/v7"
	"github.com/sirupsen/logrus"
)

// create elasticsearch client.
func newElasticClient(c config.Config) (*elasticsearch.Client, error) {
	// Declare an Elasticsearch configuration
	cfg := elasticsearch.Config{
		Addresses: []string{c.Query.DefaultElasticSearchHost},
		// Username: "user",
		// Password: "pass",
	}

	// Instantiate a new Elasticsearch client object instance
	client, err := elasticsearch.NewClient(cfg)
	if err != nil {
		logrus.Info(fmt.Sprintf("Elasticsearch connection error: %+v", err))
		return nil, errorx.Error(errorx.ERROR_ELASTIC_INIT_CLIENT_FAILED, "")
	}

	// Have the client instance return a response
	res, err := client.Info()
	if err != nil {
		logrus.Info(fmt.Sprintf("Elasticsearch client.Info() error: %+v", err))
		return nil, errorx.Error(errorx.ERROR_ELASTIC_INIT_FAILED, "")
	}

	defer res.Body.Close()

	if res.IsError() {
		// Check response status
		logrus.Info(fmt.Sprintf("Elasticsearch client.Info() res.IsError(), err: %s, %+v", res.Status(), res))
		return nil, errorx.Error(errorx.ERROR_ELASTIC_INIT_FAILED, "")
	}

	logrus.Info(fmt.Sprintf("Elasticsearch client.Info() client response: %+v", res))

	// Get cluster info
	var r map[string]interface{}
	// Deserialize the response into a map.
	if err := json.NewDecoder(res.Body).Decode(&r); err != nil {
		logrus.Info(fmt.Sprintf("Elasticsearch Error parsing the response body: %+v", err))
		return nil, errorx.Error(errorx.ERROR_ELASTIC_INIT_FAILED, "")
	}

	// Print client and server version numbers.
	logrus.Info(fmt.Sprintf("Elasticsearch Client: %s", elasticsearch.Version))
	logrus.Info(fmt.Sprintf("Elasticsearch Server: %s", r["version"].(map[string]interface{})["number"]))
	// logrus.Println(strings.Repeat("~", 37))

	return client, nil
}
